package session;

import entity.User;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.*;
import java.util.Random;

/**
 * @author Miss Chen
 * @version 1.0
 * @date 2024年09月04日11:23
 */
@WebServlet("*.code")
public class CodeServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path=request.getServletPath();
        if("/show.code".equals(path)){
            showCode(request,response);
        }
        if("/login.code".equals(path)){
            login(request,response);
        }
        if("/register.code".equals(path)){
            register(request,response);
        }
        if("/logout.code".equals(path)){
            logout(request,response);
        }
        if("/logout2.code".equals(path)){
            logout2(request,response);
        }
    }
    public void showCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Random random=new Random();

        //在内存中定义一个画板
        BufferedImage image=new BufferedImage(50,25,BufferedImage.TYPE_INT_RGB);

        //获取画板中对应的画笔
       Graphics graphics= image.getGraphics();

       //指定画笔所填充的矩形区域
       graphics.fillRect(0,0,50,25);

       //设置画笔的颜色，设置一个随机色
        graphics.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));

        //设置画笔的对应的字体样式
        graphics.setFont(new Font("宋体",Font.BOLD+Font.ITALIC,18));

        //验证码内容，要求:随机数字或者英文字母
        String s="abcdefghijklmnopqrstuvwxyz0123456789";
        StringBuffer buffer=new StringBuffer();
        for(int i=0;i<4;i++){
            buffer.append(s.charAt(random.nextInt(s.length())));
        }
        //生成验证码后需要与用户输入的验证码进行比较
        request.getSession().setAttribute("code",buffer.toString());
        System.out.println("验证码:"+buffer);

        //将随机生成的字符绘制到图片中
        graphics.drawString(buffer.toString(),5,18);


        //输出图片
        ImageIO.write(image,"JPEG",response.getOutputStream());

    }
    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取请求中的数据
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        String code=request.getParameter("code");

        //获取验证码图片中的内容
        String image= (String) request.getSession().getAttribute("code");

        //校验验证码
        if(!code.equals(image)){
            request.setAttribute("loginMsg","验证码不正确");
            request.getRequestDispatcher("/session/login.jsp").forward(request,response);
            return;
        }

        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        String url="jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn= DriverManager.getConnection(url,"root","root");
            String sql=new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from t_user ")
                    .append(" where username=? ")
                    .append(" and password=? ")
                    .toString();
            ps=conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            rs=ps.executeQuery();
            if(rs.next()){
                User user=new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                //当用户成功后，将查询出来的数据保存到session中取
                request.getSession().setAttribute("user",user);
                response.sendRedirect(request.getContextPath()+"/session/main.jsp");
                return;
            }

            request.setAttribute("loginMsg","用户名或者密码错误");
            request.getRequestDispatcher("/session/login.jsp").forward(request,response);

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("loginMsg","服务器内部异常");
            request.getRequestDispatcher("/session/login.jsp").forward(request,response);
        } finally {
            //关闭释放资源
        }
    }
    public void register(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        request.setCharacterEncoding("utf-8");
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        String phone=request.getParameter("phone");
        String address=request.getParameter("address");
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        String url="jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn= DriverManager.getConnection(url,"root","root");
            //判断用户名是否重复
            // 可以先根据当前用户名查询对应的用户信息
            String sql=new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from t_user ")
                    .append(" where username=? ")
                    .toString();
            ps=conn.prepareStatement(sql);
            ps.setString(1,username);
            rs=ps.executeQuery();
            if(rs.next()){
                request.setAttribute("registerMsg","该用户已经被注册");
                request.getRequestDispatcher("/session/register.jsp").forward(request,response);
                return;
            }
            //如果用户名尚未注册，则执行注册业务
            sql=new StringBuffer()
                    .append(" insert into t_user ")
                    .append(" (username,password,phone,address) ")
                    .append(" values  ")
                    .append(" (?,?,?,?) ")
                    .toString();
            ps=conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            ps.setString(3,phone);
            ps.setString(4,address);
            ps.executeUpdate();
            response.sendRedirect(request.getContextPath()+"/session/login.jsp");

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("registerMsg","服务器内部异常");
            request.getRequestDispatcher("/session/register.jsp").forward(request,response);
        }finally {
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(ps!=null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //方式一：直接移除session的user信息
        request.getSession().removeAttribute("user");
        response.sendRedirect(request.getContextPath()+"/session/main.jsp");
    }
    public void logout2(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //方式二：直接清除原有的session，创建一个新的session
        request.getSession().invalidate();
        response.sendRedirect(request.getContextPath()+"/session/main.jsp");
    }
}
